package bdd.sql.server.hibernate;

import network.messages.KrakenServerMsg;

import java.net.URL;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import bdd.sql.server.bean.Camera;
import bdd.sql.server.bean.Encryption;
import bdd.sql.server.bean.Keystore;
import bdd.sql.server.bean.RequestToken;
import bdd.sql.server.bean.ServerCentral;
import bdd.sql.server.bean.Log;
import bdd.sql.server.bean.ServerSite;
import bdd.sql.server.bean.ServerStorage;
import bdd.sql.server.bean.User;
import bdd.sql.server.bean.User_Log;
import bdd.sql.server.bean.Video;
import bdd.sql.server.bean.ServerWeb;

/**
 * Wrapper pour démarrer Hibernate dans un bloc statique d'initialisation.
 * @author Scub-Foundation
 */
public class HibernateUtilOld {

	private static SessionFactory sessionFactory;
	private static ServiceRegistry serviceRegistry;
	private static URL path;

	static {
		try {
			//compatible pour nous deux, normalement, en utilisation locale
			//path = KrakenServerMsg.class.getResource("../../hibernate_standalone_SQLServer.cfg.xml");
			//path = KrakenServerMsg.class.getResource("../../hibernate_standalone.cfg.xml");
			
			//utilisation via le .jar...
			//path = KrakenApplet.class.getResource("/hibernate_standalone.cfg.xml");
			path = KrakenServerMsg.class.getResource("/hibernate_standalone_SQLServer.cfg.xml");
			//System.out.println("DEBUG "+path);

			// On créé une factory de type Annotation afin de les prendre en charge
			Configuration configuration = new Configuration();
			configuration.configure(path);
			serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();        
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
			//sessionFactory = new AnnotationConfiguration().configure(path).buildSessionFactory();
			System.out.println("\n\n\n\n\n\n\n\n\nLAAAAAAAAAAAA\n\n\n\n\n\n\n\n\n");
		} /*catch (Throwable ex) {
			// Log exception!
			System.out.println("DEBUG Err "+path);
			throw new ExceptionInInitializerError(ex);
		}*/ catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Accesseur.
	 * @return la session existante
	 * @throws HibernateException
	 */
	public static Session getSession() throws HibernateException {
		return sessionFactory.openSession();
	}

	/**
	 * Ferme la session Hibernate.
	 * @throws HibernateException
	 */
	public static void closeSession() throws HibernateException {
		sessionFactory.close();
	}
	
	/**
	 * Test si un champ existe déjà dans la base de données.
	 * @param session
	 * @param className
	 * @param field
	 * @param value
	 * @return boolean
	 * @throws HibernateException
	 */
	public static Boolean isFieldAlreadyExists(Session session, String className, String field, Object value) throws HibernateException  {
		try {
			@SuppressWarnings("unchecked")
			List<User> resultats = session.createCriteria(Class.forName(className)).add(Restrictions.eq(field, (Object)value)).list();
			if(resultats.size() > 0)	return true;
			else	return false;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return true;
		}
	}
	
	
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		try {
			Session session = HibernateUtilOld.getSession();
			
			List<Camera> list1 = session.createCriteria(Camera.class).list();
			System.out.println("\tCamera");
			for(Camera c : list1)
				System.out.println(c);
			
			List<Encryption> list4 = session.createCriteria(Encryption.class).list();
			System.out.println("\tEncryption");
			for(Encryption c : list4)
				System.out.println(c);
			
			List<ServerCentral> list5 = session.createCriteria(ServerCentral.class).list();
			System.out.println("\tGlobalServer");
			for(ServerCentral c : list5)
				System.out.println(c);
			
			List<Log> list6 = session.createCriteria(Log.class).list();
			System.out.println("\tLog");
			for(Log c : list6)
				System.out.println(c);
			
			List<ServerSite> list8 = session.createCriteria(ServerSite.class).list();
			System.out.println("\tSiteServer");
			for(ServerSite c : list8)
				System.out.println(c);
			
			List<ServerStorage> list9 = session.createCriteria(ServerStorage.class).list();
			System.out.println("\tStorageServer");
			for(ServerStorage c : list9)
				System.out.println(c);
			
			List<Video> list13 = session.createCriteria(Video.class).list();
			System.out.println("\tVideo");
			for(Video c : list13)
				System.out.println(c);
				
			List<Keystore> list16 = session.createCriteria(Keystore.class).list();
			System.out.println("\tKeystore");
			for(Keystore c : list16)
				System.out.println(c);
			
			List<ServerWeb> list14 = session.createCriteria(ServerWeb.class).list();
			System.out.println("\tWebServer");
			for(ServerWeb c : list14)
				System.out.println(c);
			
			List<User> list12 = session.createCriteria(User.class).list();
			System.out.println("\tUser");
			for(User c : list12)
				System.out.println(c);
			
			List<User_Log> list11 = session.createCriteria(User_Log.class).list();
			System.out.println("\tUser_Log");
			for(User_Log c : list11)
				System.out.println(c);
			
			List<RequestToken> list15 = session.createCriteria(RequestToken.class).list();
			System.out.println("\tRequest");
			for(RequestToken c : list15)
				System.out.println(c);
			
			
			/*Transaction tx = session.beginTransaction();
			User userAdmin = new User("admin", "a", "admin", Rank.Administrateur, Civility.Monsieur, StringUtils.generateRandomString(12));
			session.save(userAdmin);
			userAdmin.setUser_pwd(PasswordSecurity.sha256("admin",userAdmin.getUser_seedPwd()));
			userAdmin.setUser_firstcon(0);
			session.save(userAdmin);
			tx.commit();*/
			session.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
